package com.vcit.system.service.grade.impl;

import java.util.ArrayList;
import java.util.List;
import com.vcit.common.utils.DateUtils;
import com.vcit.common.utils.SecurityUtils;
import com.vcit.system.domain.grade.TStudentGrade;
import com.vcit.system.domain.vo.StudentGradeVo;
import com.vcit.system.mapper.grade.TStudentGradeMapper;
import com.vcit.system.service.grade.ITStudentGradeService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.vcit.system.domain.vo.StudentGradeImportVo;
import com.vcit.system.mapper.clazz.TClazzMapper;
import com.vcit.system.mapper.term.TermMapper;
import com.vcit.system.mapper.course.TCourseMapper;
import com.vcit.system.domain.clazz.TClazz;
import com.vcit.system.domain.term.Term;
import com.vcit.system.domain.course.TCourse;
import org.springframework.web.multipart.MultipartFile;
import com.vcit.common.core.domain.AjaxResult;
import com.vcit.common.utils.poi.ExcelUtil;
import java.math.BigDecimal;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.vcit.system.domain.grade.TClazzTermCourse;
import com.vcit.system.mapper.grade.TClazzTermCourseMapper;


/**
 * 学生课程成绩Service业务层处理
 * 
 * @author dff
 * @date 2025-02-11
 */
@Service
public class TStudentGradeServiceImpl implements ITStudentGradeService
{
    private static final Logger log = LoggerFactory.getLogger(TStudentGradeServiceImpl.class);
    @Autowired
    private TStudentGradeMapper tStudentGradeMapper;
    @Autowired
    private TClazzMapper clazzMapper;
    @Autowired
    private TermMapper termMapper;
    @Autowired
    private TCourseMapper courseMapper;
    @Autowired
    private TClazzTermCourseMapper clazzTermCourseMapper;

    /**
     * 查询学生课程成绩
     * 
     * @param id 学生课程成绩主键
     * @return 学生课程成绩
     */
    @Override
    public TStudentGrade selectTStudentGradeById(Long id)
    {
        return tStudentGradeMapper.selectTStudentGradeById(id);
    }

    @Override
    public StudentGradeVo selectStudentGradeVoById(Long id) {
        return tStudentGradeMapper.selectStudentGradeInfoById(id);
    }

    /**
     * 查询学生课程成绩列表
     * 
     * @param tStudentGrade 学生课程成绩
     * @return 学生课程成绩
     */
    @Override
    public List<StudentGradeVo> selectTStudentGradeList(StudentGradeVo tStudentGrade)
    {
        StudentGradeVo studentGradeVo = new StudentGradeVo();
        BeanUtils.copyProperties(tStudentGrade, studentGradeVo);
        return tStudentGradeMapper.selectTStudentGradeAllInfo(studentGradeVo);
    }

    /**
     * 新增学生课程成绩
     * 
     * @param tStudentGrade 学生课程成绩
     * @return 结果
     */
    @Override
    public int insertTStudentGrade(TStudentGrade tStudentGrade)
    {
        tStudentGrade.setCreateTime(DateUtils.getNowDate());
        return tStudentGradeMapper.insertTStudentGrade(tStudentGrade);
    }

    /**
     * 修改学生课程成绩
     * 
     * @param tStudentGrade 学生课程成绩
     * @return 结果
     */
    @Override
    public int updateTStudentGrade(TStudentGrade tStudentGrade)
    {
        tStudentGrade.setUpdateTime(DateUtils.getNowDate());
        return tStudentGradeMapper.updateTStudentGrade(tStudentGrade);
    }

    /**
     * 批量删除学生课程成绩
     * 
     * @param ids 需要删除的学生课程成绩主键
     * @return 结果
     */
    @Override
    public int deleteTStudentGradeByIds(Long[] ids)
    {
        return tStudentGradeMapper.deleteTStudentGradeByIds(ids);
    }

    /**
     * 删除学生课程成绩信息
     * 
     * @param id 学生课程成绩主键
     * @return 结果
     */
    @Override
    public int deleteTStudentGradeById(Long id)
    {
        return tStudentGradeMapper.deleteTStudentGradeById(id);
    }

    @Override
    public AjaxResult importStudentGrades(MultipartFile file) {
        try {
            // 1. 解析Excel为VO列表
            ExcelUtil<StudentGradeImportVo> util = new ExcelUtil<>(StudentGradeImportVo.class);
            List<StudentGradeImportVo> importList = util.importExcel(file.getInputStream());
            List<String> errorRows = new ArrayList<>();
            List<TStudentGrade> gradeList = new ArrayList<>();
            int rowNum = 2; // Excel首行为标题
            int skipCount = 0;
            int successCount = 0;
            // 2. 遍历每一行，查找ID、校验、去重
            for (StudentGradeImportVo vo : importList) {
                // 查找班级、学期、课程ID
                TClazz clazz = clazzMapper.selectTClazzByName(vo.getClazzName());
                Term term = termMapper.selectTermByName(vo.getTermName());
                TCourse course = courseMapper.selectTCourseByName(vo.getCourseName());
                if (clazz == null || term == null || course == null || vo.getStudentSno() == null) {
                    errorRows.add("第" + rowNum + "行：基础信息未找到");
                    log.warn("第{}行基础信息未找到：{}", rowNum, vo);
                    rowNum++;
                    continue;
                }
                // 新增：校验班级学期是否分配了该课程
                TClazzTermCourse ctcQuery = new TClazzTermCourse();
                ctcQuery.setClazzId(clazz.getId());
                ctcQuery.setTermId(term.getId());
                ctcQuery.setCourseId(course.getId());
                List<TClazzTermCourse> ctcList = clazzTermCourseMapper.selectList(ctcQuery);
                if (ctcList == null || ctcList.isEmpty()) {
                    errorRows.add("第" + rowNum + "行：该班级本学期未分配课程【" + vo.getCourseName() + "】，不能导入成绩");
                    log.warn("第{}行班级学期未分配课程：{}", rowNum, vo);
                    rowNum++;
                    continue;
                }
                // 检查是否已存在该学生该学期该课程成绩，避免重复
                TStudentGrade query = new TStudentGrade();
                query.setStudentSno(vo.getStudentSno());
                query.setTermId(term.getId());
                query.setCourseId(course.getId());
                List<TStudentGrade> exist = tStudentGradeMapper.selectTStudentGradeList(query);
                if (exist != null && !exist.isEmpty()) {
                    skipCount++;
                    log.info("第{}行数据重复跳过：学号={},学期={},课程={}", rowNum, vo.getStudentSno(), vo.getTermName(), vo.getCourseName());
                    rowNum++;
                    continue;
                }
                // 组装成绩对象
                TStudentGrade grade = new TStudentGrade();
                grade.setStudentSno(vo.getStudentSno());
                grade.setTermId(term.getId());
                grade.setCourseId(course.getId());
                grade.setExamScore(vo.getExamScore());
                grade.setCreateId(SecurityUtils.getUserId());
                grade.setCreateTime(DateUtils.getNowDate());
                gradeList.add(grade);
                rowNum++;
            }
            // 3. 插入成绩数据（批量插入）
            if (!gradeList.isEmpty()) {
                try {
                    successCount = tStudentGradeMapper.batchInsert(gradeList);
                } catch (Exception e) {
                    log.error("批量插入成绩失败", e);
                    errorRows.add("批量插入失败: " + e.getMessage());
                }
            }
            // 4. 统计和返回结果
            String msg = "导入成功：" + successCount + "条，跳过重复：" + skipCount + "条";
            if (!errorRows.isEmpty()) {
                return AjaxResult.error(msg + "，失败：" + errorRows.size() + "条", errorRows);
            }
            return AjaxResult.success(msg);
        } catch (Exception e) {
            log.error("导入学生成绩异常", e);
            return AjaxResult.error("导入失败：" + e.getMessage());
        }
    }
}
